<template>
    <div id="security-loan" class="order-content">
        <div class="top" style="width: 100%; overflow: auto">
            <el-row class="row-height top-row" style="border-bottom: 1px solid #c9c9c9">
                <el-col :span="8" class="col-box" style="border-right: 1px solid #c9c9c9">
                    <h3 class="title">风控指令:<el-divider></el-divider></h3>
                    <el-form label-width="110px" size="small">
                        <el-row class="form-row">
                            <el-col>
                                <el-form-item label="外部指令序号:"
                                    ><el-input v-model="riskOrderForm.outerOrderCode" disabled size="mini"></el-input
                                ></el-form-item>
                            </el-col>
                        </el-row>
                        <el-row class="form-row">
                            <el-col :span="12">
                                <el-form-item label="产品序号:">
                                    <RiskEntryInput @set-entry-data="getEntryslist" :returnDatas="riskOrderForm.fundCode" />
                                    <!-- <el-select v-model="riskOrderForm.fundCode" filterable @change="handleFundCodeChange" size="mini">
                    <el-option v-for="i in fundCodeSelectData" :key="i.fundCode" :label="i.fundCode + ' ' + i.fundNameSt" :value="i.fundCode">
                    </el-option>
                  </el-select> -->
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="期限:">
                                    <el-input-number
                                        v-model="riskOrderForm.deadline"
                                        size="mini"
                                        controls-position="right"
                                        :min="1"
                                        step-strictly="true"
                                        :class="['font-color-' + textColor]"
                                    >
                                        <template slot="append">天</template>
                                    </el-input-number>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row class="form-row">
                            <el-col :span="12">
                                <el-form-item label="组合编码:">
                                    <el-select v-model="riskOrderForm.fundAccountCode" size="mini">
                                        <el-option
                                            v-for="i in computedFundAccountCodeSelectData"
                                            :key="i.fundAccountCode"
                                            :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                            :value="i.fundAccountCode"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="费率:">
                                    <el-input v-model="riskOrderForm.rate" size="mini" :class="['font-color-' + textColor]">
                                        <template slot="append">%</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row class="form-row">
                            <el-col :span="12">
                                <el-form-item label="证券代码:">
                                    <el-select
                                        v-model="riskOrderForm.stockCode"
                                        @change="handleStockCodeChange"
                                        filterable
                                        remote
                                        :remote-method="searchStockCodeList"
                                        :loading="selectLoading"
                                        style="width: 100%"
                                        size="mini"
                                    >
                                        <el-option
                                            v-for="i in stockCodeSelectData"
                                            :key="i.stockCode"
                                            :label="i.stockCode + ' ' + i.stockNameSt"
                                            v-model="i.stockCode"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="融出数量:">
                                    <el-input v-model="riskOrderForm.orderAmount" size="mini" :class="['font-color-' + textColor]">
                                        <template slot="append">股</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row class="form-row"> </el-row>
                        <el-row class="form-row">
                            <el-col :span="12">
                                <el-form-item label="委托方向:">
                                    <el-select v-model="riskOrderForm.orderDirection" size="mini" :class="['font-color-' + textColor]">
                                        <el-option
                                            v-for="i in investSelectData"
                                            :key="i.dictKey"
                                            :label="i.dictKey + ' ' + i.dictKeyName"
                                            :value="i.dictKey"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="业务类型:">
                                    <el-select v-model="riskOrderForm.businessType" size="mini">
                                        <el-option
                                            v-for="i in businessTypeData"
                                            :key="i.dictKey"
                                            :label="i.dictKey + ' ' + i.dictKeyName"
                                            :value="i.dictKey"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row class="form-row">
                            <el-col :span="12">
                                <el-form-item label="交易对手:">
                                    <el-select
                                        v-model="riskOrderForm.opponentCode"
                                        filterable
                                        remote
                                        :remote-method="getOpponentCode"
                                        :loading="selectLoading"
                                        size="mini"
                                    >
                                        <el-option
                                            v-for="i in opponentCodeSelectData"
                                            :key="i.dictKey"
                                            :label="i.dictKey + ' ' + i.dictKeyName"
                                            :value="i.dictKey"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row class="form-row">
                            <el-col>
                                <el-form-item label="备注:"><el-input v-model="riskOrderForm.remark" size="mini"></el-input></el-form-item>
                            </el-col>
                        </el-row>
                        <el-row class="form-row" style="float: right">
                            <el-button v-authCode="B_0039" @click="handleRemake" size="mini">重置</el-button>
                            <el-button v-authCode="B_0041" @click="handleSubmit('1')" type="primary" size="mini">试算</el-button>
                            <el-button v-authCode="B_0040" @click="handleSubmit('2')" type="primary" size="mini">下单</el-button>
                        </el-row>
                    </el-form>
                </el-col>
                <el-col :span="16" class="col-box security-box">
                    <h3 class="title" style="margin-top: 6px">持仓信息:<el-divider></el-divider></h3>
                    <risk-table :msg="positionsListMsg" @getList="getPositionList"></risk-table>
                </el-col>
            </el-row>
        </div>
        <el-row class="row-height bottom-row">
            <el-col class="col-box">
                <h3 class="title">
                    <el-row>
                        <el-col :span="3">风控结果:<status-tag :code="riskResult"></status-tag></el-col>
                        <el-col :span="5">
                            <span>试算/下单时间: </span>
                            <span style="color: red">{{ calcTime }}</span>
                        </el-col>
                        <el-col :span="5">
                            <span>计算耗时: </span>
                            <span style="color: red">{{ takeTime }}</span>
                        </el-col>
                        <el-col :span="4"
                            >条目检查数:
                            <span v-show="riskResListMsg.returnData.data.length" style="color: red">{{
                                riskResListMsg.returnData.data.length
                            }}</span></el-col
                        >
                    </el-row>
                    <el-divider></el-divider>
                </h3>
                <div>
                    <RiskResult :riskResultTable="riskResultTable" :stockInfoPojo="stockInfoPojo" />
                </div>
            </el-col>
        </el-row>
    </div>
</template>
<script lang="ts">
import { getUser } from '@/utils/user-util';
import { Component, Vue, Watch } from 'vue-property-decorator';
import RiskTable from '@/common/components/risk-table.vue';
import { SGU_CACHE, objToArr } from '@/utils/diction-const-util';
import Invest from '@/common/dict/invest';
import { UUID, NumberToWords, getCurrentPageData, numberFormat, unitShow, highlightColor } from '@/utils/tools';
import StatusTag from './components/status-tag.vue';
import BranchTag from './components/branch-tag.vue';
import RiskResult from './components/risk-result.vue';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import MeasureColumnsUtil from './utils/measure-columns-util';

@Component({
    name: 'SecurityLoan',
    components: {
        RiskTable,
        StatusTag,
        BranchTag,
        RiskResult,
        RiskEntryInput,
    },
})
export default class SecurityLoan extends Vue {
    private Invest: any = new Invest();

    // 风控指令表单
    riskOrderForm = {
        orderType: '', // 下单类型
        outerOrderCode: '自动生成', // 外部指令序号
        fundCode: '', // 产品序号
        fundAccountCode: '', // 组合编码
        orderDirection: '', // 委托方向
        remark: '', // 备注
        stockType: '',
        businessType: '', // 业务类型
        deadline: '', // 期限
        rate: '', // 费率
        orderAmount: '', // 融出数量
        opponentCode: '', // 交易对手
        // orderPriceType: '',//价格模式
        orderBalance: '0', // 指令金额
        orderUser: getUser().userCode, // 下单人
        orderLevel: '1', // 指令优先级
        orderPurpose: '1', // 指令用途
        requestId: '',
        reportCode: '',
        investType: '',
        marketCode: '',
    };

    stockInfoPojo: any = {};
    positionList: any[] = [];
    textColor: string = ''; // 红绿凸显
    MeasureColumnsUtil = new MeasureColumnsUtil();
    fundInfo: any = {};
    // 持仓信息相关
    positionsListMsg = {
        url: '/baseInfomation/securityLoan/',
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.MeasureColumnsUtil.securityLoanPositionColumns,
        height: '200px',
        // 隐藏页码
        hidePage: false,
        checked: { on: false, option: false },
    };

    // 风控结果相关
    riskResListMsg = {
        url: '/dataEngine/order/securityloanOrder',
        returnData: { data: [] },
        dataKey: 'data',

        height: '350px',
        // 隐藏页码
        hidePage: true,
        checked: { on: false, option: false },
    };

    // 证券代码下拉框数据相关
    stockCodeMsg = {
        url: '/original/stock/list',
        submit: {
            paging: { total: 0, currentPage: 1, totalPage: 0, pageSize: 20 },
            multStockType: [1],
            multMarketCode: ['1', '2'],
            stockCode: '',
        },
    };

    // 委托方向下拉数据
    investSelectData = [
        {
            dictKey: 'l',
            dictKeyName: '证券转融通融出',
        },
    ];

    // 业务类型下拉数据
    businessTypeData = [
        {
            dictKey: '1',
            dictKeyName: '交易所网上',
        },
    ];

    fundCodeSelectData: any[] = []; // 产品序号下拉框数据

    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据

    stockCodeSelectData: any[] = []; // 证券代码下拉框数据

    opponentCodeSelectData: any[] = []; // 交易对手方下拉数据

    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态

    calcTime: string = ''; // 下单/试算时间

    takeTime: string | number = ''; // 计算耗时

    riskResult: string | number = ''; // 风控结果

    entryType = {}; // 风险类型字典
    compareDirection = {}; // 比较方向字典
    entryTypeArr: any[] = [];
    ThresholdTypeArr: any[] = [];
    tableKey: number = 0;

    // 图标dom
    private iconDom: any = null;

    // 风控结果表数据
    private riskResultTable: any[] = [];

    async mounted() {
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
        // 获取风险类型字典
        this.entryType = this.Invest.entryType;
        this.entryTypeArr = this.objToArr(this.Invest.entryType);
        // 获取比较方向字典
        this.compareDirection = this.Invest.CompareDirection;

        this.ThresholdTypeArr = this.objToArr(this.Invest.ThresholdType);
        this.getstockCodeList();
        this.getOpponentCode('');
    }

    // 转表格筛选下拉框数据
    objToArr(param) {
        let list = [];
        for (let key in param) {
            list.push({ label: param[key], value: key });
        }
        return list;
    }

    // 组合编码下拉框计算属性
    get computedFundAccountCodeSelectData() {
        return this.fundAccountCodeSelectData[this.riskOrderForm.fundCode] || [];
    }

    // 监听 组合编码计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedFundAccountCodeSelectData', { immediate: true, deep: true })
    watchcomputedFundAccountCode(newData) {
        if (newData && newData.length) {
            this.riskOrderForm.fundAccountCode = newData[0].fundAccountCode;
        }
    }

    /**
     * 判断字段颜色
     */
    @Watch('riskOrderForm', { immediate: true, deep: true })
    handleFieldColor() {
        console.log(this.riskOrderForm.orderDirection);
        if (this.riskOrderForm.orderDirection == 'l') {
            this.textColor = highlightColor()[2];
        } else {
            this.textColor = highlightColor()[0];
        }
    }

    //   获取交易对手方信息
    private getOpponentCode(value: string) {
        this.$axios
            .post('/dict/opponent/select', {
                dictKey: value,
                dictKeyName: value,
            })
            .then((res: any) => {
                this.opponentCodeSelectData = res;
            });
    }

    getEntryslist(val: any) {
        this.riskOrderForm.fundCode = val;
        this.handleFundCodeChange(val);
    }

    // 产品序号选中事件 => 请求持仓信息
    handleFundCodeChange(e: string) {
        if (e) {
            this.$axios(this.positionsListMsg.url + e).then(async (res: any) => {
                let data = [];
                if (res.length) {
                    await this.handleFundInfo(e);
                    data = res.map(item => {
                        item.fundNameSt = this.fundInfo.fundNameSt;
                        return item;
                    });
                }
                this.positionList = data;
                this.getPositionList({
                    currentPage: 1,
                    pageSize: 25,
                });
            });
        } else {
            this.positionList = [];
            this.positionsListMsg.returnData.data = [];
            this.positionsListMsg.returnData.total = 0;
        }
    }

    async handleFundInfo(val: string) {
        return this.$axios
            .get('/fundInfo/list/byUser/like?fundCodeOrName=' + encodeURIComponent(val))
            .then((res: any) => {
                this.fundInfo = res.find(item => item.fundCode == val) || {};
            })
            .catch(err => {
                console.log(err);
            });
    }

    getPositionList(pages) {
        this.positionsListMsg.returnData.data = getCurrentPageData(this.positionList, pages.currentPage, pages.pageSize);
        this.positionsListMsg.returnData.total = this.positionList.length;
    }

    // 证券代码选中事件
    private handleStockCodeChange(e: string) {
        this.riskOrderForm.orderDirection = '';

        this.$axios('/baseInfomation/stockCode/' + e).then((res: any) => {
            if (res) {
                if (res.foreverStock) {
                    this.riskOrderForm.investType = '3';
                } else {
                    this.riskOrderForm.investType = '1';
                }
            }
            let st = this.stockCodeSelectData.find(item => item.stockCode === e);
            this.stockInfoPojo[e] = st.stockNameSt;

            let stockType = null;
            for (let i = 0; i < this.stockCodeSelectData.length; i++) {
                const ele = this.stockCodeSelectData[i];
                if (ele.stockCode === e) {
                    stockType = ele.stockType;
                    this.riskOrderForm.marketCode = ele.marketCode;
                    this.riskOrderForm.reportCode = ele.reportCode;
                    this.riskOrderForm.stockType = ele.stockType;
                    break;
                }
            }
        });
    }

    // 获取证券代码下拉框数据
    getstockCodeList() {
        this.selectLoading = true;
        this.$axios.post(this.stockCodeMsg.url, this.stockCodeMsg.submit).then((res: any) => {
            this.stockCodeSelectData = res.list || [];
            this.selectLoading = false;
        });
    }

    // 证券代码下拉框远程搜索
    searchStockCodeList(e: string) {
        this.stockCodeMsg.submit.stockCode = e;
        this.getstockCodeList();
    }

    filterEntryTypeMethod({ value, row, column }) {
        return row.entryType == value;
    }

    // 表格列筛选数据
    filterHandler({ option, row, column }) {
        console.log(column);

        const property = column['property'];
        return row[property].includes(option.data);
    }

    // 重置指令表单
    private handleRemake() {
        this.riskOrderForm = {
            orderType: '', // 下单类型
            outerOrderCode: '自动生成', // 外部指令序号
            fundCode: '', // 产品序号
            fundAccountCode: '', // 组合编码
            orderDirection: '', // 委托方向
            remark: '', // 备注
            stockType: '',
            businessType: '', // 业务类型
            deadline: '', // 期限
            rate: '', // 费率
            orderAmount: '', // 融出数量
            opponentCode: '', // 交易对手
            // orderPriceType: '',//价格模式
            orderBalance: '0', // 指令金额
            orderUser: getUser().userCode, // 下单人
            orderLevel: '1', // 指令优先级
            orderPurpose: '1', // 指令用途
            requestId: '',
            reportCode: '',
            investType: '',
            marketCode: '',
        };
        this.positionsListMsg.returnData.data = [];
        this.positionsListMsg.returnData.total = 0;
    }

    // 校验提交参数
    verifyInstructionParam() {
        let param = this.riskOrderForm;
        // if (!param.orderType) {
        //   this.yh_message_error('下单类型不可为空');
        //   return false;
        // }
        if (!param.outerOrderCode) {
            this.yh_message_error('外部指令序号不可为空');
            return false;
        }
        if (!param.fundCode) {
            this.yh_message_error('产品代码不可为空');
            return false;
        }
        if (!param.fundAccountCode) {
            this.yh_message_error('组合编码不可为空');
            return false;
        }
        if (!param.orderDirection) {
            this.yh_message_error('委托方向不可为空');
            return false;
        }
        if (!param.businessType) {
            this.yh_message_error('业务类型不可为空');
            return false;
        }
        if (!param.deadline) {
            this.yh_message_error('期限不可为空');
            return false;
        }
        if (!param.rate) {
            this.yh_message_error('费率不可为空');
            return false;
        }
        if (!param.orderAmount) {
            this.yh_message_error('融出数量不可为空');
            return false;
        }
        return true;
    }

    // 提交事件
    handleSubmit(orderType: string) {
        // 下单类型
        this.riskOrderForm.orderType = orderType;

        // 计算耗时
        let start = window.performance.now();
        // 下单号
        this.riskOrderForm.outerOrderCode = 'fg' + UUID() + '-' + new Date().getTime();
        // 请求id
        this.riskOrderForm.requestId = 'rfg' + UUID() + '-' + new Date().getTime();

        // 校验参数规则
        if (!this.verifyInstructionParam()) {
            return;
        }
        // 获取当前提交时间 (试算/下单时间)
        // 补零
        let fillZero = n => {
            let result = n.toString().length === 1 ? '0' + n : n;
            return result;
        };
        // 时间戳转换 yyyy-MM-dd
        let formatTime = (t = new Date()) => {
            let d = new Date(t);
            let year = d.getFullYear();
            let month = d.getMonth() + 1;
            let date = d.getDate();
            let hours = d.getHours();
            let minutes = d.getMinutes();
            let seconds = d.getSeconds();
            let result = `${year}-${fillZero(month)}-${fillZero(date)} ${fillZero(hours)}:${fillZero(minutes)}:${fillZero(seconds)}`;
            return result;
        };
        this.calcTime = formatTime(new Date());
        // 提交指令 => 获取风控结果
        this.$axios.post(this.riskResListMsg.url, this.riskOrderForm).then((res: any) => {
            this.yh_message_success('指令信息提交成功');
            // 风控结果
            this.riskResult = res.thresholdType;
            // 计算耗时
            let end = window.performance.now();
            this.takeTime = ((end - start) / 1000).toFixed(3) + '秒';

            let data = res.resultList || [];

            // 根据产品代码 匹配产品名称
            data.forEach(ele => {
                ele.requestId = res.requestId;
                // 风险类型
                ele.entryType2 = this.entryType[ele.entryType];
                // 比较方向
                ele.compareType2 = this.compareDirection[ele.compareType];

                for (let i = 0; i < this.fundCodeSelectData.length; i++) {
                    const item = this.fundCodeSelectData[i];
                    if (ele.fundCode === item.fundCode) {
                        ele.fundNameSt = item.fundNameSt;
                    }
                }
            });
            this.$set(this.riskResListMsg.returnData, 'data', data);
            this.riskResultTable = this.riskResListMsg.returnData.data;
        });
    }
}
</script>
<style lang="scss" scoped>
@import './style/measure';

#security-loan {
    width: 100%;
    height: 100vh;
    min-height: 600px;
    .col-box {
        // height: 100%;
        padding: 20px 10px;
        .el-divider {
            margin: 0;
            margin-top: 5px;
        }
        .form-row {
            margin-top: 3px;
            .el-form-item--small {
                margin: 0;
                & /deep/ .el-form-item__label {
                    color: #575757;
                }
                & /deep/ .el-input__inner {
                    height: 28px;
                    line-height: 28px;
                }
                .font-color-red {
                    /deep/ input {
                        color: red !important;
                    }
                    /deep/ .el-input-group__append {
                        color: red !important;
                    }
                }
                .font-color-green {
                    /deep/ input {
                        color: green !important;
                    }
                    /deep/ .el-input-group__append {
                        color: green !important;
                    }
                }
            }
        }
    }
}
</style>
